﻿using JESAI.Core.Logging;
using JESAI.Core.Modularity;
using System.ComponentModel;
using JESAI.Logs.NLog;
using NLog.Extensions.Logging;

namespace JESAI.Platform.WebApi.Modules
{
    /// <summary>
    /// 日志模块
    /// </summary>
    [Description("日志模块")]
    [DependsOnModule(typeof(AspNetCoreModule))]
    public class LogModule : JESAIModule
    {
        /// <summary>
        /// 模块级别。级别越小越先启动
        /// </summary>
        public override ModuleLevel Level => ModuleLevel.Framework;

        /// <summary>
        /// 模块启动顺序。模块启动的顺序先按级别启动，同一级别内部再按此顺序启动，
        /// 级别默认为0，表示无依赖，需要在同级别有依赖顺序的时候，再重写为>0的顺序值
        /// </summary>
        public override int Order => 4;

        /// <summary>
        /// 添加服务。将模块服务添加到依赖注入服务容器中
        /// </summary>
        /// <param name="services">服务集合</param>
        public override IServiceCollection AddServices(IServiceCollection services)
        {
            //services.AddJESAINLog();
           
            services.AddSingleton<ILogContextAccessor, LogContextAccessor>();

            services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddNLog();
            });
            return services;
        }
    }

    /// <summary>
    /// 日志上下文访问器
    /// </summary>
    public class LogContextAccessor : ILogContextAccessor
    {
        /// <summary>
        /// 当前日志上下文
        /// </summary>
        private readonly AsyncLocal<LogContext> _currentLogContext;

        /// <summary>
        /// 初始化一个<see cref="LogContextAccessor"/>类型的实例
        /// </summary>
        public LogContextAccessor()
        {
            _currentLogContext = new AsyncLocal<LogContext>();
        }

        /// <summary>
        /// 日志上下文
        /// </summary>
        public LogContext Context
        {
            get
            {
                return _currentLogContext.Value ??= new LogContext();
            }
            set
            {
                _currentLogContext.Value = value;
            }
        }
    }
}
